<?php

declare (strict_types=1);

namespace app\common\service\bangdou;

use app\api\model\UserOauth as UserOauthModel;
use app\api\service\order\PaySuccess as OrderPaySuccesService;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\library\helper;
use app\common\model\OrderSub as OrderSubModel;
use app\common\model\OrderGoods as OrderGoodsModel;
use app\common\model\UserOauth;
use app\common\service\bangdou\BdMember as BdMemberService;
use app\common\service\bangdou\Common;
use app\store\model\Goods as GoodsModel;

/**
 * @time:2024/01/16 17:38
 * @Author:wuqicheng
 */
class BdPay extends Common
{
    /**
     * 用户在邦豆生活级别
     * @param null $type
     * @return array|string[]|\string[][]
     */
    public static function userBdGrade($type = null)
    {
        $rabate = ['1'=>['id'=>'1','name'=>'普通会员','rabate_bd'=>'0'],
            '2'=>['id'=>'2','name'=>'黄金会员','rabate_bd'=>'0.1'],
            '3'=>['id'=>'3','name'=>'铂金会员','rabate_bd'=>'0.2'],
            '4'=>['id'=>'4','name'=>'钻石会员','rabate_bd'=>'0.3']];
        if($type){
            if(isset($rabate[$type])){
                return $rabate[$type];
            }else{
                return [];
            }
        }else{
            return $rabate;
        }
    }

    public static function bangddouPay($pay_data,$user_id){
        if(empty($user_id)){
            throwError('用户不存在');
        }
        $user = UserOauthModel::getOauth($user_id, getPlatform());

        if(!isset($user['bd_uid']) || empty($user['bd_uid'])){
            throwError('用户bd_uid不存在');
        }else{
            $bd_uid = $user['bd_uid'];
        }
        $token_array = self::createToken($bd_uid);
        $type = [7,6,5];
        if(in_array($pay_data['bdType'],$type)){
            $payType = $pay_data['bdType'];
        } else{
            $payType = 1;
        }
        if($pay_data['pay_money'] == '0.00'){//微信支付金额为0.00
            $payData = array( ['payType'=>$payType,'payMoney'=>$pay_data['dk_money']]);
        }else{
            if($pay_data['dk_money'] != '0.00'){
                $payData = array( ['payType'=>$payType,'payMoney'=>$pay_data['dk_money']],
                    ['payType'=>'1','payMoney'=>$pay_data['pay_money']]);
            }else{
                $payData = array( ['payType'=>'1','payMoney'=>$pay_data['pay_money']]);
            }
        }

        $params['platform'] = 'shopping';
        $params['orderNo'] = $pay_data['order_no'];
        $params['payData'] = $payData;
        $params['openId'] = $user['oauth_id'];
        $params['timestamp'] = time();
        $sign = self::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url = app()->config->get('app.bd_api_url').'/Order/Order/pay';
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = helper::httpRequest($url, json_encode($params), $headers);
        $res = json_decode($result, true);
        if($res['state'] && $res['data']['thirdPartyPayment']==false){
            // 获取订单详情
            $service = new OrderPaySuccesService($pay_data['order_no']);
            $res_data['transaction_id'] = $res['data']['data'];
            //三券支付成功处理订单信息
            $status = $service->onPaySuccess(OrderPayTypeEnum::WECHAT,$res_data);
            if (!$status) {
                throwError($service->getError());
            }
            $res['data'] = null;
        }
        return $res;
    }

    //批量订单确认收货送邦豆
    public static function saveGiveBd($orderList){
        foreach ($orderList as $order) {
            $order_sub = OrderSubModel::getOrderSubBy($order['order_id']);
            if(empty($order_sub)){
                continue;
            }
            if($order_sub['give_bdtime']>0){//邦豆已送
                continue;
            }
            $is_rebate = true;
            if($order_sub['deduction_value']>0){//如果商品使用了邦豆与微信组合支付将不返豆
                $is_rebate = false;
            }
            $user_grade = 1;//用户在邦豆生活会员等级
            if($order['user_id']){
                $bd_uid = 0;
                $userInfo = UserOauth::getOauth($order['user_id'],'MP-WEIXIN');
                if (isset($userInfo['bd_uid']) && !empty($userInfo['bd_uid'])) {
                    $bd_uid = $userInfo['bd_uid'];
                }
                $bd_user = BdMemberService::getUserProperty($bd_uid);//获取用户等级
                $user_grade = isset($bd_user['memberType'])?$bd_user['memberType']:1;
            }
            $rebate['give_bd'] = '0.00';//该订单返邦豆
            $rebate['give_coupon'] = '0.00';//该订单返现金券
            //循环订单商品
            foreach ($order['goods'] as $goods) {
                if (
                    !empty($goods['refund'])
                    && $goods['refund']['type'] == 10      // 售后类型：退货退款
                    && $goods['refund']['audit_status'] == 10  // 商家审核：已同意
                ) {
                    continue;//退货退款订单不出返豆
                }else if($is_rebate || $goods['is_bd'] == 2){//订单没有使用邦豆支付或者商品不支持邦豆支付就返豆
                    //计算商品赠送多少邦豆
                    $rebate_data = self::goodsRebateBdNumber($user_grade,$goods['total_pay_price'],$goods['rebate_type']);
                    $rebateData['give_bd'] = $rebate_data['give_bd'];
                    $rebateData['give_coupon'] = $rebate_data['give_coupon'];
                    $model = new OrderGoodsModel();
                    //记录每个商品返豆数量
                    $model->where('order_goods_id', $goods['order_goods_id'])->update($rebateData);
                    $rebate['give_bd'] = bcadd($rebate['give_bd'],$rebate_data['give_bd'],2);
                    $rebate['give_coupon'] =  bcadd($rebate['give_coupon'],$rebate_data['give_coupon'],2);
                }else{
                    continue;//退货退款订单不出返豆
                }
            }

            $token_array = self::createTokenByuserId($order['user_id']);
            $pay_data['timestamp'] = time();
            $pay_data['platform'] = 'shopping';
            $pay_data['rewardBangdouTotal'] = $rebate['give_bd'];
            $pay_data['rewardCouponTotal'] = $rebate['give_coupon'];
            $pay_data['orderNo'] = $order['order_no'];
            $pay_data['storeId'] = $order['store_id'];
            $pay_data['organId'] = self::ORGANID;
            $sign = self::getBangDouApiSign($pay_data);
            $pay_data['sign'] = $sign;
            $headers = [
                'Content-Type: application/json',
                "Authorization: Bearer {$token_array['token']}"
            ];

            $api_url = app()->config->get('app.bd_api_url').'/Order/Order/sendBangdouAndCoupon';
            $result = helper::httpRequest($api_url, json_encode($pay_data), $headers);
            $res = json_decode($result, true);
            $log_file = runtime_root_path() .'api/log/give_user_bd_'.date('y-m-d').'.log';
            file_put_contents($log_file, print_r($res, true)."\n", FILE_APPEND);
            if($res['state'] == true){
                $data['give_bd'] = $rebate['give_bd'];//赠送的邦豆
                $data['give_coupon'] = $rebate['give_coupon'];//赠送的邦豆
                $data['give_bdtime'] = time();
                $data['state'] = 30;
                OrderSubModel::updateOrderSubBy($order['order_id'],$data);
            }
        }
        return true;
    }



    /**
     * 计算订单商品返豆数量
     * @param $user_grade 用户等级
     * @param $total_pay_price 订单总金额
     * @param $rebate_type 返豆类型
     */
    public static function goodsRebateBdNumber($user_grade,$total_pay_price,$rebate_type){
        $user_grade = self::userBdGrade($user_grade);
        $rebate_info = GoodsModel::goodsRebateType($rebate_type);
        $data['give_bd'] = '0.00';
        $data['give_coupon'] = '0.00';
        if (isset($user_grade['rabate_bd']) && isset($rebate_info['rabate_bd'])){
            $data['grade_bd'] = bcmul($total_pay_price, $user_grade['rabate_bd'], 2);//会员等级赠送邦豆
            $data['good_bd'] = bcmul($total_pay_price, $rebate_info['rabate_bd'], 2);//商品类型赠送邦豆
            $data['give_coupon'] = bcmul($total_pay_price, $rebate_info['rabate_coupon'], 2);//商品类型赠送优惠券
            $data['give_bd'] = bcadd($data['grade_bd'],$data['good_bd'],2);//合计赠送邦豆

        }
        return $data;
    }


    /**
     * @param $orderId
     * @param $transaction_id 微信订单号
     * @return false|mixed
     * 订单全额退款
     */
    /*public static function bangddouRefund($orderId,$transaction_id){
        $order = OrderSubModel::getOrderSubBy($orderId);
        if(empty($order)){
            return false;
        }
        $token_array = self::createTokenByuserId($order['user_id']);
        if($order['pay_money']>0 && $order['deduction_value']>0){
            $params['payData'] = [['payType'=>1,'payMoney'=>$order['pay_money']],
                                  ['payType'=> $order['bd_type'],'payMoney'=>$order['deduction_value']]];
        }else{
            if($order['payMoney']>0){
                $params['payData'] = [['payType'=>1,'payMoney'=>$order['pay_money']]];
            }
            if($order['deductionValue']>0){
                $params['payData'] = [['payType'=>$order['bd_type'],'payMoney'=>$order['deduction_value']]];
            }
        }
        $params['organId'] = self::ORGANID;
        $params['storeId'] = $order['store_id'];
        $params['orderId'] = $order['order_id'];
        $params['orderNo'] = $order['order_no'];
        $params['outTardeNo'] = $transaction_id;
        $params['platform'] = 'shopping';
        $params['timestamp'] = time();
        $sign = self::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url = app()->config->get('app.bd_api_url').'/Order/Order/refund';
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = httpRequest($url, json_encode($params), $headers);
        $res = json_decode($result, true);
        log_record($result);
        if($res['state'] == true){
            $data['state'] = 40;
            return OrderSubModel::updateOrderSubBy($orderId,$data);
        }
        return false;
    }*/
    /**
     * @param $orderId
     * @param $money 退款金额
     * @param $transaction_id 微信订单号
     * @return false|mixed
     * 订单部分退款，优先退邦豆
     */
    public static function bangdouRefund($orderInfo,$transaction_id,$money){
        if(isset($orderInfo['order_id'])){
            $order = OrderSubModel::getOrderSubBy($orderInfo['order_id']);
        }
        if(empty($order)){
            throwError('订单不存在');
            return false;
        }
//        if($order['state'] != 20){
//            throwError('订单状态异常');
//            return false;
//        }
        if(is_null($money)){
            $money = $orderInfo['pay_price'];
            $data['state'] = 40;//已付款订单取消
        }else{
            $data['state'] = 50;//用户退款
        }


        $payMoney = bcadd($order['pay_money'],$order['deduction_value'],2) ;
        if($money>$payMoney){//退款金额大于支付金额
            throwError('退款金额大于支付金额');
            return false;
        }

        if(isset($orderInfo['is_bd']) && $orderInfo['is_bd'] == '2'){
            $params['payData'] = [['payType' => 1, 'payMoney' => $money]];
            $cash = $money;
        }else {
            //退款优先三券
            $cash = '0.00';//退现金
            $deductionValue = '0.00';//退三券
            if (in_array($order['bd_type'], ['6', '7'])) {//邦豆券和现金券
                if ($order['deduction_value'] >= $money) {
                    $params['payData'] = [['payType' => $order['bd_type'], 'payMoney' => $money]];
                    $deductionValue = $money;
                } else {
                    $cash = bcsub($money, $order['deduction_value'], 2);//退微信
                    $deductionValue = $order['deduction_value'];
                    $params['payData'] = [['payType' => 1, 'payMoney' => $cash],
                        ['payType' => $order['bd_type'], 'payMoney' => $order['deduction_value']]];
                }
            } elseif ($order['bd_type'] == 5) {//退礼金券
                if ($order['deduction_value'] >= $money) {
                    $coupon = floor($money / 5) * 5;
                    $cash = bcsub($money, $coupon, 2);//退微信
                } else {
                    $coupon = $order['deduction_value'];
                    $cash = bcsub($money, $order['deduction_value'], 2);//退微信
                }

                if ($cash > 0 && $coupon > 0) {
                    $params['payData'] = [['payType' => 1, 'payMoney' => $cash],
                        ['payType' => $order['bd_type'], 'payMoney' => $coupon]];
                } elseif ($cash > 0) {
                    $params['payData'] = [['payType' => 1, 'payMoney' => $cash]];
                } else {
                    $params['payData'] = [['payType' => $order['bd_type'], 'payMoney' => $coupon]];
                }
                if ($coupon > 0) {
                    $deductionValue = $coupon;
                }

            } else {
                if($money <= $order['pay_money']){
                    $params['payData'] = [['payType' => 1, 'payMoney' => $money]];
                    $cash = $money;
                }else{
                    throwError('订单不合法');
                    return false;
                }

            }
        }

        $params['organId'] = self::ORGANID;
        $params['storeId'] = $order['store_id'];
        $params['orderId'] = $order['order_id'];
        $params['orderNo'] = $order['order_no'];
        $params['weixinMoney'] = $order['pay_money'];
        $params['outTardeNo'] = $transaction_id;
        $params['tmpOutTardeNo'] = $order['tmp_out_tarde_no'] ?? '';
        $params['platform'] = 'shopping';
        $params['timestamp'] = time();

        $sign = self::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url = app()->config->get('app.bd_api_url').'/Order/Order/refund';
        $token_array = self::createTokenByuserId($order['user_id']);
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = helper::httpRequest($url, json_encode($params), $headers);
        $res = json_decode($result, true);
        $log_file = runtime_root_path() .'api/log/bd_wx_Refund_'.date('y-m-d').'.log';
        file_put_contents($log_file, print_r($res, true)."\n", FILE_APPEND);
        if($res['state'] == true){
            $data['state'] = '50';
            $data['pay_money'] = bcsub($order['pay_money'],$cash,2);
            $data['deduction_value'] = bcsub($order['deduction_value'],$deductionValue,2);
            OrderSubModel::updateOrderSubBy($orderInfo['order_id'],$data);
            return true;
        }else{
            throwError($res['message']);
        }
        return false;
    }
    /*public static function bdPay($pay_data,$api_url){
        if($pay_data['userId']){
            $user = (new \yii\db\Query())
                ->select('bd_uid,openId,uniacid')
                ->from('{{%ybo2ov2_member}}')
                ->where('id=:id', [':id' => $pay_data['userId']])->one();
        }
        if(!isset($user['bd_uid']) || empty($user['bd_uid'])){
            return false;
        }
        $token_array = self::createToken($user['bd_uid']);
        $pay_data['timestamp'] = time();
        $pay_data['platform'] = 'shopping';
        $pay_data['recommendUserId'] = $user['bd_uid'];
        $pay_data['openId'] = $user['openId'];
        $sign = self::getBangDouApiSign($pay_data);
        $pay_data['sign'] = $sign;
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = httpRequest($api_url, json_encode($pay_data), $headers);
        $res = json_decode($result, true);
        return $res;
    }*/
}